<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/11/12
 * Time: 16:10
 */
namespace App\Models;

Class Liveroom extends BaseModel{

    protected $table = 'Liveroom';
    public $timestamps = false;

    public function __construct( )
    {
        parent::__construct();
    }

    /**
     * 按条件查询单条数据
     */
    public function getOne(array $where, $fields = '*')
    {
        return $this->multiSelect($fields)->multiWhere($where)->first();
    }

    /**
     * 按条件查询全部数据,根据配置显示条数显示
     */
    public function getList(array $where = [], $fields = '*', $order = '', $pageSize = '')
    {
        if ($pageSize) {
            return $this->multiSelect($fields)->multiWhere($where)->multiOrder($order)->paginate($pageSize);
        } else {
            return $this->multiSelect($fields)->multiWhere($where)->multiOrder($order)->get();
        }
    }

    /**
     * 根据条件删除数据
     */
    public function del(array $where)
    {
        return $this->multiWhere($where)->delete();
    }

    /**
     *插入数据
     */
    public function add($data)
    {
//        dd($data);
        return $this->insertGetId($data);
    }

    /**
     *更新数据
     */
    public function up($where, $data)
    {
        return $this->multiWhere($where)->update($data);
    }

    /**
     * 获取和
     */
    public function getSum($where, $field)
    {
        return $this->multiWhere($where)->sum($field);
    }

    /**
     * 字段递加
     */
    public function inc($where, $field, $n)
    {
        return $this->multiWhere($where)->increment($field, $n);
    }

    // 获取正在直播的直播间
    public function getOnlineRoom(){
        $room = $this->getList(['status'=>1],'',[],8);
        // 获得直播间信息
        foreach ($room as $k => $v) {
            $room[$k]['roominfo'] = $this->getOne(['id'=>$v['roomnum']]);
        }
        return $room;
    }

    /**
     * 开播
     */
    public function StartLive($requst){
         $where['roomnum'] = $requst['num'];
         $where['uid']     = session('loginId');
         // 判断当前是否有直播未结束
         $isLiveing = $this->getOne(['roomnum'=>$requst['num'],'status'=>1]);
         if ($isLiveing) {
             $res['code'] = 400;
             $res['msg']  = '当前的直播间正在直播中';
             return $res;
         }
         $roomModel = new Roomnum();
         $roominfo  = $roomModel->getOne(['num'=>$requst['num'],'uid'=>session('loginId')]);
         $result = $this->getOne($where);
         if ($result) {
             // 生成推流地址
             $push = $this->getPushUrl(config('app.tx.bizid'),$roominfo['num'],config('app.tx.key'),date('Y-m-d H:i:s',time()+3600*24));
             $data['starttime'] = time();
             $data['status'] = 1;
             $resu = $this->up($where,$data);
             if ($resu) {
                  // 写入直播记录
                  $Liverecore = new Liverecord();
                  $data['roomtype'] = $roominfo['cate'];
                  $data['uid']      = $roominfo['uid'];
                  $data['title']    = $roominfo['title'];
                  $data['roomnum']  = $roominfo['num'];
                  $Liverecore->addLiveRecord($data);
                  $res['code'] = 200;
                  $res['msg']  = '开播成功';
                  $res['pushurl'] = $push;
                  return $res;
             }
             $res['code'] = 400;
             $res['msg']  = '开播失败';
             return $res;
             die;
         }
        $data['uid'] = session('loginId');
        $data['roomnum'] = $requst['num'];
        $data['starttime'] = time();
        $data['snap'] = 0;
        $data['roomtype'] = $roominfo['cate'];
        $data['needmoney'] = 0;
        $data['roompsw'] = 0;
        $data['online_num'] = 0;
        $data['status'] = 1;

        // 生成推流地址
        $push = $this->liveroom->getPushUrl(config('app.tx.bizid'),$roominfo['num'],config('app.tx.key'),date('Y-m-d H:i:s',time()+3600*24));
        $resulte = $this->add($data);
        if ($resulte) {
            // 写入直播记录
            $Liverecore = new Liverecord();
            $data['roomtype'] = $roominfo['cate'];
            $data['uid']      = $roominfo['uid'];
            $data['title']    = $roominfo['title'];
            $data['roomnum']  = $roominfo['num'];
            $Liverecore->addLiveRecord($data);

            $res['code'] = 200;
            $res['msg']  = '开播成功';
            $res['pushurl'] = $push;
            return $res;
        }else{
            $res['code'] = 400;
            $res['msg']  = '开播失败';
            return $res;
        }
    }

    /**
     * 关播处理
     */
    public function endLive($num){
         $liveRoomInfo = $this->getOne(['roomnum'=>$num['num'],'uid'=>session('loginId')]);
         if ($liveRoomInfo['status'] != 1) {
               return ['code'=>400,'msg'=>'状态不正确'];
         }
         $updata['status'] = 0;
         $res = $this->up(['roomnum'=>$num['num'],'uid'=>session('loginId')],$updata);
         if ($res) {
             $Liverecore = new Liverecord();
             $liverecrd = $Liverecore->up(['roomnum'=>$num['num'],'status'=>1],['status'=>0,'endtime'=>time()]);
             return ['code'=>200,'msg'=>'关播成功'];
         }
         return ['code'=>400,'msg'=>'状态未成功'];
    }



    /**
     * 获取推流地址
     * 如果不传key和过期时间，将返回不含防盗链的url
     * @param bizId 您在腾讯云分配到的bizid
     *        streamId 您用来区别不同推流地址的唯一id
     *        key 安全密钥
     *        time 过期时间 sample 2016-11-12 12:00:00
     * @return String url */
    function getPushUrl($bizId, $streamId, $key = null, $time = null){
        if($key && $time){
            $txTime = strtoupper(base_convert(strtotime($time),10,16));
            //txSecret = MD5( KEY + livecode + txTime )
            //livecode = bizid+"_"+stream_id  如 8888_test123456
            $livecode = $bizId."_".$streamId; //直播码
            $txSecret = md5($key.$livecode.$txTime);
            $ext_str = "?".http_build_query(array(
                    "bizid"=> $bizId,
                    "txSecret"=> $txSecret,
                    "txTime"=> $txTime
                ));
        }
        $livecode = $bizId."_".$streamId; //直播码
        return "rtmp://".$bizId.".livepush.myqcloud.com/live/".$livecode.(isset($ext_str) ? $ext_str : "");
    }

    /**
     * 获取播放地址
     * @param bizId 您在腾讯云分配到的bizid
     *        streamId 您用来区别不同推流地址的唯一id
     * @return String url */
    function getPlayUrl($bizId, $streamId){
        $livecode = $bizId."_".$streamId; //直播码
        return array(
            "rtmp://".$bizId.".liveplay.myqcloud.com/live/".$livecode,
            "http://".$bizId.".liveplay.myqcloud.com/live/".$livecode.".flv",
            "http://".$bizId.".liveplay.myqcloud.com/live/".$livecode.".m3u8"
        );
    }
    
    /**
     * 获取Top数据 [萌新榜，女神榜，男神榜]
     */
    public static function getTopData()
    {
           $memberidarr = [];
           $memberType = [
               "sex" => 1,
               "sex1" => 2
           ];
           $member = new Member();
           foreach ($memberType as $v){
                 $where['sex'] = $v;
                 $memberList = $member->where($where)->get(['id']);
                 $memberList = $memberList->toArray();
                 $memberid = [];
                 foreach ($memberList as $v) {
                      $memberid[] = $v['id'];
                 }
                 $memberidarr[] = $memberid;
           }
//           dd($memberidarr);

    }



}